import service.ExecService;
import service.impl.ExecServiceImpl;
import service.impl.ExpireKeyManageServiceImpl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 服务端 套接字(url+port)等待连接、接收命令、发送数据
 */
public class Server {
    private static byte[] buffer=new byte[1024];
    private static int read=0;
    private static ExecService execService=new ExecServiceImpl();
    private static ExpireKeyManageServiceImpl keyManageService=new ExpireKeyManageServiceImpl();

    public static void main(String[] args) {
        //初始化配置
        initConfig();
        //初始化服务
        initConnect();
    }

    private static void initConfig() {
        //过期key管理
        keyManageService.start();
    }

    private static void initConnect() {
        int port=8888;
        try(ServerSocket serverSocket=new ServerSocket(port)) {
            System.out.println("Server is listening on port " + port);
            while (true){
                //阻塞等待连接
                try(Socket accept=serverSocket.accept()) {
                    System.out.println("New client connected");
                    acceptData(accept);
                }catch (IOException e) {
                    System.out.println("Exception caught when trying to accept a new client");
                }
            }
        }catch (IOException e){
            System.out.println("Exception caught when trying to listen on port " + port);
        }
    }

    private static void acceptData(Socket accept) throws IOException {
        InputStream in = accept.getInputStream();
        OutputStream out = accept.getOutputStream();
        while ((read=in.read(buffer,0,buffer.length))!=-1){
            String data = new String(buffer, 0, read);
            //字符串数据预处理
            String[] split = data.split("\\s+");
            String resultData = execService.exec(split);
            //参数提前劫持
            out.write(resultData.getBytes(StandardCharsets.UTF_8));
            out.write("END".getBytes());
        }
    }
}
